import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:psi/http/service_api.dart';
import 'package:psi/services/share_preference_service.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../entity/common_resp.dart';
import '../routes/app_pages.dart';
import '../utils/utils.dart';
import '../utils/widget_util.dart';

class Http {

  factory Http() => _getInstance();
  static Http? _instance;

  static _getInstance() {
    _instance ??= Http._();
    return _instance;
  }

  RestClient get serviceApi => _serviceApi!;
  RestClient? _serviceApi;

  static const int CONNECT_TIMEOUT = 50000;
  static const int RECEIVE_TIMEOUT = 30000;
  static bool showLogoutAlert = false;

  Http._() {

    // dio.interceptors.add(DioLogInterceptor());
    _serviceApi = RestClient(createDio());

  }

  static Dio createDio() {
    var options = BaseOptions(
        connectTimeout: Duration(milliseconds: CONNECT_TIMEOUT), receiveTimeout: Duration(milliseconds: RECEIVE_TIMEOUT));
    final dio = Dio(options);
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          try {
            String? token = SharePreferenceService.getToken();
            if (token != null) {
              options.headers['Authorization'] = token;
              handler.next(options);
            } else {
              handler.next(options);
            }
          } catch(e) {
            LogUtil.e(e);
            handler.next(options);
          }
        },
        onResponse: (resp, handler) async {
          if (resp.statusCode == 200) {
            try {
              final commonResp = CommonResp.fromJson(resp.data);
              if (commonResp.code == 0) {
                return handler.next(resp); // continue
              } else if (commonResp.code == 401) {
                Utils.hideLoading();
                if ((SharePreferenceService.getToken()?.isEmpty ?? true) && Get.currentRoute != PageNames.login) {
                  if (!showLogoutAlert) {
                    showLogoutAlert = true;
                    WidgetUtil.showAlert(message: '登录已过期，请重新登录', onDone: () {
                      showLogoutAlert = false;
                      Utils.userLogic.logout();
                      Get.offAllNamed(PageNames.login);
                    }, onCancel: () {
                      showLogoutAlert = false;
                    });
                  }
                } else {
                  Utils.showToast(commonResp.message);
                  Utils.userLogic.logout();
                  Get.offAllNamed(PageNames.login);
                }
                return handler.reject(DioException(requestOptions: resp.requestOptions));
              } else {
                Utils.showToast(commonResp.message);
                return handler.next(resp);
              }
            } catch (e) {
              Utils.showToast("服务器数据错误");
              return handler.next(resp);
            }
          }
          Utils.showToast("服务器连接失败，请稍后再试");
          return handler.next(resp);
          // 如果你想终止请求并触发一个错误,你可以 reject 一个`DioError`对象,如`handler.reject(error)`，
          // 这样请求将被中止并触发异常，上层catchError会被调用。
        },
      ),
    );

    dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));

    return dio;
  }



}